package hikari.preferences;

import com.gooddies.persistence.Properties;
import com.gooddies.wiring.annotations.Wire;
import com.gooddies.wiring.annotations.WiringComponent;
import hikari.persistence.file.FileSection;
import hikari.persistence.file.HikariFile;
import hikari.preferences.device_parameters.DeviceParameters;
import hikari.utils.Utils;
import java.io.File;
import java.io.IOException;

/**
 * @author sad
 */
@WiringComponent(singleton = true)
public class GameProperties {
    private DeviceParameters deviceParameters = new DeviceParameters();
    private String baseFolder;
    private String projectPath;
    @Wire
    private Utils utils;

    public String getProjectName() {
        return utils.getFileNameWithoutExtension(projectPath);
    }

    public String getProjectPath() {
        return projectPath;
    }

    public String getBaseFolder() {
        return baseFolder;
    }

    public String getMediaFolder() {
        return utils.combinePaths(baseFolder, "/media/");
    }
    
    public String getCppProjectFolder() {
        return utils.combinePaths(baseFolder, "/cpp/");
    }
    
    public boolean isProjectSaved(){
        return projectPath!=null && !projectPath.isEmpty();
    }

    public String getSceneFolder() {
        return utils.combinePaths(getMediaFolder(),"scene");
    }

    public void setBaseFolder(String baseFolder) {
        baseFolder = baseFolder.replace('\\', '/');
        if (!baseFolder.endsWith("/")) {
            baseFolder = baseFolder + "/";
        }
        this.baseFolder = baseFolder;
    }

    public DeviceParameters getDeviceParameters() {
        return deviceParameters;
    }

    public void setDeviceParameters(DeviceParameters deviceParameters) {
        this.deviceParameters = deviceParameters;
    }

    public void openProject(String path) throws IOException {
        setBaseFolder(utils.getFilePath(path));
        projectPath = path;
        deviceParameters = loadDeviceParameters(path);
        Properties.get().putString("project", path);
    }

    private DeviceParameters loadDeviceParameters(String path) throws IOException {
        DeviceParameters params = new DeviceParameters();
        HikariFile file = new HikariFile(new File(path));
        file.openForReading();
        FileSection gamePropertiesSection = file.readSection(file.getChunk("deviceProperties"));
        params.load(gamePropertiesSection);
        file.close();
        return params;
    }
}
